//
//  MinePhoneNumberChangeViewController.swift
//  House
//
//  Created by 吕品 on 16/7/11.
//  Copyright © 2016年 ZJWL. All rights reserved.
//

import UIKit
import MBProgressHUD
class MinePhoneNumberChangeViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource, MixViewProtocol {
    var naviBar = BaseTitleNavigationBar()
    
    fileprivate var tableView = UITableView()
    fileprivate let imageArray = [UIImage.init(named: "MinePhoneNumber"), UIImage.init(named: "MineCodeImage")]//titleimage array
    fileprivate let placeArray = ["请输入新手机号", "请输入验证码"]// textfield placeholder array
    fileprivate var yzm = ""  //yzm
    fileprivate var phone = ""//phone number when receive yzm
    override func viewDidLoad() {
        super.viewDidLoad()
        automaticallyAdjustsScrollViewInsets = false
        tabbarHidden = true
        
        naviBar = BaseTitleNavigationBar.init(frame: CGRect.init(x: 0, y: 0, width: self.view.bounds.size.width, height: 64), withTitleStr: "手机号码修改")
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(back(tap:)))
        naviBar.leftView.addGestureRecognizer(tap)
        view.addSubview(naviBar)
        
        tableView = UITableView.init(frame: CGRect.init(x: 0, y: 64, width: self.view.bounds.size.width, height: self.view.bounds.size.height - 64), style: .plain)
        view.addSubview(tableView)
        let rightButton = UIButton.init(type: .system)
        naviBar.addSubview(rightButton)
        rightButton.setTitleColor( .white, for: .normal)
        rightButton.setTitle("保存", for: .normal)
        rightButton.titleLabel?.font = UIFont.systemFont(ofSize: 17, weight: 15)
        rightButton.addTarget(self, action: #selector(submit), for: .touchUpInside)
        rightButton.snp.makeConstraints { (make) in
            make.right.equalTo(naviBar.snp.right).offset(-10);
            make.bottom.equalTo(naviBar.snp.bottom).offset(-10);
            make.centerY.equalTo(naviBar.leftView)
            make.height.equalTo(30)
            make.width.equalTo(40)
        }

        
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(view).offset(kNaviBarHeight)
            make.left.right.bottom.equalTo(view)
        }
        tableView.delegate = self
        tableView.dataSource = self
        tableView.isScrollEnabled = false
        tableView.register(ReuseImageViewAndTextFieldTableViewCell.self, forCellReuseIdentifier: NSStringFromClass(ReuseImageViewAndTextFieldTableViewCell.self))
        tableView.tableFooterView = UIView()
        //end tableview
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return placeArray.count//phone and yzm
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(ReuseImageViewAndTextFieldTableViewCell.self)) as! ReuseImageViewAndTextFieldTableViewCell
        if (indexPath as NSIndexPath).row == 0 {//with no yzm
            cell.mixView.isShowButton = false
            let _ = cell.mixView.textField.rx.text.subscribe(onNext: { (text) in
                if text != "" {
                    let cell = tableView.visibleCells.last as! ReuseImageViewAndTextFieldTableViewCell
                    cell.isSure = RegConditionManager.checkPhoneNumber(text)
                }
                }, onError: { (error) in

                }, onCompleted: { 

                }, onDisposed: { 

            })
        } else {// indexPath.row == 1 with yzm
            cell.delegate = self
        }
        //cell.mixview and their propertys set values
        cell.mixView.imageView.image = imageArray[(indexPath as NSIndexPath).row]!
        cell.mixView.textField.placeholder = placeArray[(indexPath as NSIndexPath).row]
        cell.selectionStyle = .none//selectedstyle
        cell.tag = tagManager + (indexPath as NSIndexPath).row//tag (for after using)
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }
    func didPassValue(isSure: Bool) {
        if isSure {
            getCode()
        } else {
            let hud = MBProgressHUD.showAdded(to: view, animated: true)
            hud.mode = .text
            hud.label.text = "请输入正确的手机号"
            self.hide(withTitle: "请输入正确的手机号")
        }
    }
    //submit revise request
    func submit() -> Void {
        let phoneNum = (view.viewWithTag(1000) as! ReuseImageViewAndTextFieldTableViewCell).mixView.textField.text!//phonenum
        let code = (view.viewWithTag(1001) as! ReuseImageViewAndTextFieldTableViewCell).mixView.textField.text!//current yzm
        let hud = MBProgressHUD.showAdded(to: view, animated: true)
        hud.label.text = "正在提交验证,请稍后"
        if phoneNum == ""  {
            self.hide(withTitle: "手机号码不能为空")
        } else if code == "" {
            self.hide(withTitle: "请输入验证码")
        } else if yzm != code || phoneNum != phone {
            self.hide(withTitle: "输入的信息有误")
        } else {
            if phone ==  phoneNum && code == yzm{
                NetRequest.updateOrGetInformation(fromUrl: PHPHeader.manager().revisePhonePHP, withParameters: ["id": UserInfoManager.shared().uid, "phone": phoneNum], success: { (task, response) in
                    if response is NSDictionary {
                        let reponseObj = response as! NSDictionary
                        if reponseObj["flg"] as! NSNumber == NSNumber.init(value: 1) {
                            self.hide(withTitle: "更改成功")
                           DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: { 
                            print(self.navigationController?.popToRootViewController(animated: true))
                           }) 
                        } else {
                            self.hide(withTitle: "更改失败")
                        }
                    }


                    }, failure: { (task, error) in
                        print(error)
                        self.hide(withTitle: "提交失败")
                })
            } else {
                self.hide(withTitle: "输入的信息有误")//public func
            }
        }
    }
    //mixview.code button delegate func(get yzm code)
    func getCode() -> Void {
        let hud = MBProgressHUD.showAdded(to: view, animated: true)
        hud.label.text = "正在获取验证码"
        phone = (view.viewWithTag(1000) as! ReuseImageViewAndTextFieldTableViewCell).mixView.textField.text!//手机号码
        if phone == "" {
            self.hide(withTitle: "手机号不能为空")//public func
        } else {
            NetRequest.getCodeNumber(withPhoneNumber: phone, success: { (task, response) in
                if response != nil {
                    self.yzm = ((response as AnyObject).description)!
                    self.hide(withTitle: "获取成功,请注意查看短信")//public func
                } else {
                    self.hide(withTitle: "获取失败")
                }
            }) { (task, error) in
                self.hide(withTitle: "获取失败")
            }
        }
    }
    
    @objc func back(tap: UITapGestureRecognizer) -> Void {
        self.navigationController!.popViewController(animated: true)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
